interface message {
    type: string,
    data: any
}
interface listItem {
    key: number,
    select: boolean,
    from: string,
    goUrl: string,
   
}
class Main {
    list: Array<listItem>;
    crosList: Array<listItem>;
    flag:boolean
    constructor(list:Array<listItem>,crosList:Array<listItem>){
        console.log("初始化")
        console.log(JSON.stringify(list))
        console.log(JSON.stringify(crosList))
        this.list=list;
        this.crosList=crosList;
        this.flag=true;
        chrome.browserAction.setBadgeText({
            text:"OFF"
          });
        chrome.browserAction.setBadgeBackgroundColor({
            color:"#1b90ff"
        })
    }
    //请求转发
    modifyUrlListener=(evt:any)=>{
        //evt  信息
        frameId: 0
        // initiator: "https://iluna.alibaba-inc.com"  从哪个域名下发出的  
        // method: "GET"
        // parentFrameId: -1
        // requestId: "620431"
        // tabId: 10058
        // timeStamp: 1575117995745.399
        // type: "xmlhttprequest"
        // url: "https://iluna.alibaba-inc.com/manager/login"  //请求地址
        // console.log(evt.url)
        //c.alicdn.com/nrails/new-product/20190923160153/ide/index/common.css
        // console.log(evt)
        // console.log(this.list,"list")
        if(!this.flag)return ;
        let hasFrom=this.list.filter(v=>v.select).find(v=>{
            return evt.url.includes(v.from)
        })
        if(hasFrom){
            console.log(hasFrom,"hasFrom")
        }
        if(evt.url.indexOf("Xa")>=0){
            console.log(evt.url)
        }
       
        // console.log(evt.url)
        if(hasFrom){
            return {
                redirectUrl:hasFrom.goUrl     //在这里可以根据配置的域名进行重定向
            }
        }
        
    }

    //修改返回请求头
    modifyResponseHeadersListener=(details:any)=>{

        if(!this.flag)return ;
        // frameId: 507
        // initiator: "https://jing.meilipa.com"
        // method: "GET"
        // parentFrameId: 0
        // requestHeaders: Array(2)
        // 0: {name: "User-Agent", value: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) Ap…ML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"}
        // 1: {name: "Accept", value: "image/webp,image/apng,image/*,*/*;q=0.8"}
        // length: 2
        // __proto__: Array(0)
        // requestId: "10413"
        // tabId: 110
        // timeStamp: 1592038299262.711
        // type: "image"
        // url: "https://img.alicdn.com/imgextra/i1/2666087869/O1CN01F8vXfH28038683AzC_!!2666087869.jpg"       
        // console.log(details,"de")
        // // let hasAccessControlAllowOriginHeader = false;
        
        let hasFrom=this.crosList.filter(v=>v.select).find(v=>{
            return details.url.includes(v.goUrl)
        })
        let hasInitiator=this.crosList.filter(v=>v.select).find(v=>{
            return details.initiator.includes(v.goUrl)
        })

        if(hasFrom||hasInitiator){
            var responseHeaders = details.responseHeaders.map((item:any) => {
                if (item.name.toLowerCase() == 'Access-Control-Allow-Origin'.toLowerCase()) {
                  item.value ='*';
                }
                return item;
              })
              responseHeaders.push({
                  name: 'Access-Control-Allow-Origin',
                  value:'*'
              })
              responseHeaders.push({
                  name: 'Access-Control-Allow-Credentials',
                  value: '*'
              })
            
              return {
                  responseHeaders: responseHeaders
              }
        }
        
    }
    // modifyRequestHeadersListener=(details:any)=>{
    //     let hasFrom=this.list.filter(v=>v.select).find(v=>{
    //         return details.url.includes(v.from)
    //     })
    //     // console.log(evt.url)
    //     if(hasFrom){
    //         var responseHeaders = details.responseHeaders.map((item:any) => {
    //             return item;
    //           })
    //           responseHeaders.push({
    //               name: 'Content-Security-Policy',
    //               value:'upgrade-insecure-requests;connect-src *'
    //           })
              
    //           return {
    //               requestHeaders: responseHeaders
    //           }
    //     }
    // }
    registerListener = ()=>{
        //转发请求
        chrome.webRequest.onBeforeRequest.hasListener(this.modifyUrlListener) ||
        chrome.webRequest.onBeforeRequest.addListener(this.modifyUrlListener, {
        urls: ['<all_urls>']
        }, ['blocking']);
        // chrome.webRequest.onBeforeSendHeaders.hasListener(this.modifyRequestHeadersListener) ||
        //   chrome.webRequest.onBeforeSendHeaders.addListener(this.modifyRequestHeadersListener, {
        //     urls: ['<all_urls>']
        //   }, ["blocking", "requestHeaders"]);
        
        //修改回来的头部，添加跨域
        chrome.webRequest.onHeadersReceived.hasListener(this.modifyResponseHeadersListener) ||
          chrome.webRequest.onHeadersReceived.addListener(this.modifyResponseHeadersListener, {
            urls: ['<all_urls>']
          }, ["blocking", "responseHeaders", "extraHeaders"]);
        chrome.runtime.onMessage.addListener((message, sender, sendResponse)=>{
            this.handleMessage(message,sendResponse)
        })
    }
    handleMessage=(message:message,sendResponse:any)=>{
        switch(message.type){
            case "list":
                this.list=message.data;
                break;
            case "crosList":
                this.list=message.data;
                break;
            case "flag":
                this.flag=message.data;
                chrome.browserAction.setBadgeText({text:message.data?"ON":"OFF"});
            default:
                break;
        }
        sendResponse(true);
    }
}
function getFlag(){
    return new Promise((resolve,reject)=>{
        chrome.storage.sync.get(['flag'], (result)=>{
            resolve(String(result.flag)==="true"?true:false);
        });
    });
}
function getList(){
    return new Promise((resolve,reject)=>{
        chrome.storage.sync.get(['list'], (result)=>{
            resolve(Array.isArray(result.list)?result.list:[]);
        });
    });
}
function getCros(){
    return new Promise((resolve,reject)=>{
        chrome.storage.sync.get(['crosList'], (result)=>{
            resolve(Array.isArray(result.crosList)?result.crosList:[]);
        });
    });
}
Promise.all([getList(),getCros()]).then(res=>{
    let main=new Main(res[0] as Array<listItem>,res[1] as Array<listItem>);
    main.registerListener();
})

